/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package platformcomparison;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import uk.ac.liv.progenesisreader.ProgenesisFeatureListReader;

/**
 *
 * @author mackak
 */
public class PlatformComparison_features {
    
    /**
     * @param args the command line arguments
     */
   
   public static String synaptInFile = "C:/Documents and Settings/mackak/My Documents/Officials/PlatformComparison/Dong_toxo.host_SynaptG2_FeatureList_RevSearch.csv";
   //public static String synaptInFile = "C:/Documents and Settings/mackak/My Documents/Officials/PlatformComparison/PlatformComparison_DebuggingMiniFile_Synapt.csv";
   public static String orbiInFile = "C:/Documents and Settings/mackak/My Documents/Officials/PlatformComparison/Dong_toxo.human_orbi_F012849_top5rank_searchPLGSdb_FeatureList_assignedFeaturesOnly.csv";
   //public static String orbiInFile = "C:/Documents and Settings/mackak/My Documents/Officials/PlatformComparison/PlatformComparison_DebuggingMiniFile_orbi.csv";
   public static String combOutFile = "C:/Documents and Settings/mackak/My Documents/Officials/PlatformComparison/CommonFeatures_Out.csv";
   //public static String combOutFile = "C:/Documents and Settings/mackak/My Documents/Officials/PlatformComparison/PlatformComparison_DebuggingOutFile.csv";
   public static String rFileInf1 = "C:/Documents and Settings/mackak/My Documents/Officials/PlatformComparison/rFile_inf1.1_Out.csv";
   public static String rFileInf2 = "C:/Documents and Settings/mackak/My Documents/Officials/PlatformComparison/rFile_inf2.1_Out.csv";
   public static String rFileInf3 = "C:/Documents and Settings/mackak/My Documents/Officials/PlatformComparison/rFile_inf3.1_Out.csv";
   
   public static void main(String[] args) throws IOException{  
       
       //run desired functionalities from here
       findCommonFeatures(orbiInFile, synaptInFile, combOutFile);        //writes out a csv file of the proteins common to both input files (and pass an ANOVA value threshold of <0.05)
       //callRCommand(combOutFile);
   }
   
   public static void findCommonFeatures(String orbiInFile, String synaptInFile, String outFile) throws IOException{
       
        int repNum = 3;
        int conditionNum = 2;
        int timepointNum = 3;
        int resultColumnNum = repNum*(conditionNum*timepointNum);
        String colNo = Integer.toString(resultColumnNum);
        //System.out.println(colNo);
               
       //this code is written to compare two Progenesis output files
       
       File orbiFile = new File(orbiInFile);
       File synaptFile = new File(synaptInFile);
       ProgenesisFeatureListReader orbi_reader = new ProgenesisFeatureListReader(new FileReader(orbiFile));
       ProgenesisFeatureListReader synapt_reader = new ProgenesisFeatureListReader(new FileReader(synaptFile));
       int j = 0;       
       
       HashMap<String, String[]> completeMapO = orbi_reader.getCompleteMap();
       HashMap<String, String[]> completeMapS = synapt_reader.getCompleteMap();
       HashMap<String, ArrayList<String>> normAbMapO = orbi_reader.getNormalizedAbundanceMap();
       HashMap<String, ArrayList<String>> normAbMapS = synapt_reader.getNormalizedAbundanceMap();
       HashMap<String, ArrayList<String>> peptideMapO = orbi_reader.getPeptideMap();
       HashMap<String, ArrayList<String>> peptideMapS = synapt_reader.getPeptideMap();
       HashMap<String, String> mzMapO = orbi_reader.getMassOverChargeMap();
       HashMap<String, String> mzMapS = synapt_reader.getMassOverChargeMap();
       HashMap<String, ArrayList<String>> rtMapO = orbi_reader.getRetentionTimeMap();
       HashMap<String, ArrayList<String>> rtMapS = synapt_reader.getRetentionTimeMap();
       HashMap<String, String> modsMapO = orbi_reader.getModificationMap();
       HashMap<String, String> modsMapS = synapt_reader.getModificationMap();
       HashMap<String, String> chargeMapO = orbi_reader.getChargeMap();
       HashMap<String, String> chargeMapS = synapt_reader.getChargeMap();
       HashMap<String, String> idPairMap = new HashMap();
       
       Double rtotal = 0.0;
       Double av = 0.0;
       
       ArrayList<String> commonSeq = new ArrayList();
       ArrayList normAbO = new ArrayList();
       ArrayList avAbsO = new ArrayList();
       ArrayList normAbS = new ArrayList();
       ArrayList avAbsS = new ArrayList();
       ArrayList<String> idPairList = new ArrayList();
       ArrayList<String> idPairs = new ArrayList();
       
       String mzO = "";
       String mzS = "";
       
       BufferedWriter writeBuff = new BufferedWriter(new FileWriter(outFile));
       BufferedWriter inf1Buff = new BufferedWriter(new FileWriter(rFileInf1));
       BufferedWriter inf2Buff = new BufferedWriter(new FileWriter(rFileInf2));
       BufferedWriter inf3Buff = new BufferedWriter(new FileWriter(rFileInf3));
              
       HashMap<String, String> resultMap = new HashMap();
       
       String headingsO = orbi_reader.getHeadingRow3();
       String headingsS = synapt_reader.getHeadingRow3();
       
       writeBuff.write("Peptide Sequence" + "," + "Feature ID" + "," + "Charge State" + "," + "Modifications" + "," + headingsO + "Inf Av TP 1" + "," + "Inf Av TP 2" + "," + "Inf Av TP 3" + "," + "NF Av TP 1" + "," + "NF Av TP 2" + "," + "NF Av TP 3" + "," + "Peptide Sequence" + "," + "Feature ID" + "," + "Charge State" + "," + "Modifications" + "," + headingsS + "Inf Av TP 1" + "," + "Inf Av TP 2" + "," + "Inf Av TP 3" + "," + "NF Av TP 1" + "," + "NF Av TP 2" + "," + "NF Av TP 3");
       writeBuff.newLine();
       
       inf1Buff.write("Abundance_O" + "," + "Abundance_S");
       inf1Buff.newLine();
       inf2Buff.write("Abundance_O" + "," + "Abundance_S");
       inf2Buff.newLine();
       inf3Buff.write("Abundance_O" + "," + "Abundance_S");
       inf3Buff.newLine();
       
       for(String seq: peptideMapO.keySet()){
           
           if(peptideMapS.containsKey(seq)){
               //System.out.println(seq);
               commonSeq.add(seq);
           }
       }
       
        for(String comSeq : commonSeq){
                ArrayList<String> seqIDsO = (peptideMapO.get(comSeq));
                //System.out.println("O " + comSeq + "  " + seqIDsO);
                ArrayList<String> seqIDsS = (peptideMapS.get(comSeq));
                //System.out.println("S " + comSeq + "  " + seqIDsS);
                                          
                for(String idO: seqIDsO){
                    mzO = mzMapO.get(idO);                                        
                    
                    for(String idS: seqIDsS){
                        
                        double tol = 0;
                        mzS = mzMapS.get(idS);
                        Double mzDif = Math.abs(Double.parseDouble(mzS) - Double.parseDouble(mzO));
                        
                        if((Double.parseDouble(mzS) * 10 / 1000000)<(Double.parseDouble(mzO) * 10 / 1000000)){
                            tol = Double.parseDouble(mzO) * 10 / 1000000; 
                        }
                        
                        else{
                            tol = Double.parseDouble(mzS) * 10 / 1000000;
                        }
                        
                        if (mzDif<= tol){
                            if (idPairMap.get(idO)==null){
                                idPairMap.put(idO, idS);
                                resultMap.put(idO, comSeq);
                            }
                            else{
                                if((Double.parseDouble(idPairMap.get(idO)))<(Double.parseDouble(idS))){
                                    idPairMap.put(idO, idS);
                                    resultMap.put(idO, comSeq);
                                }
                                else{
                                    
                                }
                            }
                        }
                    }
                }                                             
            }
        
        int rowNum = 1;
        
        for(String idKey: idPairMap.keySet()){
            
            String idO = idKey.toString();
            //System.out.println(idO);
            String idS = idPairMap.get(idKey);
            String comSeq = resultMap.get(idKey);
                
                normAbO = normAbMapO.get(idO);
                //System.out.println(normAbO);
                normAbS = normAbMapS.get(idS);
                //System.out.println(normAbS);
                
                int tpO = 0;
                int condO = 0;
                int repO = 0;
                int indexO = 0;
                int tpS = 0;
                int condS = 0;
                int repS = 0;
                int indexS = 0;
                               
                //System.out.println(comSeq);
                
                for(tpO = 0; tpO < (timepointNum); tpO++){
                
                    for(condO = 0; condO < (conditionNum); condO++){
                        
                        for(repO = 0; repO < (repNum); repO++){
                            //System.out.println("Index = " + indexO);
                            rtotal += Double.parseDouble((normAbO.get(indexO)).toString());
                            //System.out.println(rtotal);
                            indexO++;
                        }
                        av = rtotal/repNum;
                        String avStringO = av.toString();
                        avAbsO.add(avStringO);
                        rtotal = 0.0;
                        //System.out.println(avAbsO);
                        //avAbs.clear();
                    }       
                                       
                }
                //System.out.println(rowNum);
                //rowNum++;
                
                for(tpS = 0; tpS < (timepointNum); tpS++){
                
                    for(condS = 0; condS < (conditionNum); condS++){
                        
                        for(repS = 0; repS < (repNum); repS++){
                                
                            rtotal += Double.parseDouble((normAbS.get(indexS)).toString());
                            //System.out.println("Index = " + indexS);
                            //System.out.println(rtotal);
                            indexS++;
                        }
                        av = rtotal/repNum;
                        String avStringS = av.toString();
                        avAbsS.add(avStringS);
                        rtotal = 0.0;
                        //System.out.println(avAbsS);
                        //avAbs.clear();
                    }       
                                       
                }
                
                String normAbO_trim = "";
                java.util.Iterator<String> iteratorO = normAbO.iterator();  
					   
            while (iteratorO.hasNext()) {  
                String normAbO_1 = iteratorO.next();
                //System.out.println(normAbO_1);
                String normAbO_1_trim = normAbO_1.replace("[","");
                //System.out.println(normAbO_1_trim);
                normAbO_trim += normAbO_1_trim.replace("]","") + ",";
            }
            
            //System.out.println(normAbO_trim);
            
                normAbS = normAbMapS.get(idS);
                String normAbS_trim = "";
                java.util.Iterator<String> iteratorS = normAbS.iterator();  
					   
            while (iteratorS.hasNext()) {  
                String normAbS_1 = iteratorS.next();
                String normAbS_1_trim = normAbS_1.replace("[","");
                normAbS_trim += normAbS_1_trim.replace("]","") + ",";
            }
                String chargeO = chargeMapO.get(idO);
                String chargeS = chargeMapS.get(idS);
                String modsO = modsMapO.get(idO);
                String modsS = modsMapS.get(idS);
                
                String avAbsO_trim = "";
                java.util.Iterator<String> avIteratorO = avAbsO.iterator();  
					   
            while (avIteratorO.hasNext()) {  
                String avAbsO_1 = avIteratorO.next();
                String avAbsO_1_trim = avAbsO_1.replace("[","");
                avAbsO_trim += avAbsO_1_trim.replace("]","") + ",";
            }
            //System.out.println(comSeq + " Av Ab O " + avAbsO_trim);
            //System.out.println("");
            
            String avAbsS_trim = "";
                java.util.Iterator<String> avIteratorS = avAbsS.iterator();  
					   
            while (avIteratorS.hasNext()) {  
                String avAbsS_1 = avIteratorS.next();
                String avAbsS_1_trim = avAbsS_1.replace("[","");
                avAbsS_trim += avAbsS_1_trim.replace("]","") + ",";
            }
            //System.out.println(comSeq + " Av Ab S " + avAbsS_trim);
            //System.out.println("");
                
                writeBuff.write(comSeq + "," + idO + "," + chargeO + "," + modsO + "," + normAbO_trim + avAbsO_trim + comSeq + "," + idS + "," + chargeS + "," + modsS + "," + normAbS_trim + avAbsO_trim);
                writeBuff.newLine();
                //if(comSeq.equals("VFLENVIR")){
                    //System.out.println(comSeq + " IDs " + idO + "," + idS + " charge " + chargeO + "," + chargeS);
                    //System.out.println(comSeq + "," + idO + "," + chargeO + "," + modsO + "," + normAbO_trim + "," + avAbsO_trim + "," + idS + "," + chargeS + "," + modsS + "," + normAbS_trim + "," + avAbsO_trim);
                //}
                //System.out.println(avAbsO);
                if (Double.parseDouble(normAbO.get(0).toString())>0 && Double.parseDouble(normAbS.get(0).toString())>0){
                inf1Buff.write((normAbO.get(0)).toString() + "," + (normAbS.get(0)).toString());
                inf1Buff.newLine();
                }
                if (Double.parseDouble(normAbO.get(6).toString())>0 && Double.parseDouble(normAbS.get(6).toString())>0){
                inf2Buff.write((normAbO.get(6)).toString() + "," + (normAbS.get(6)).toString());
                inf2Buff.newLine();
                }
                if (Double.parseDouble(normAbO.get(12).toString())>0 && Double.parseDouble(normAbS.get(12).toString())>0){
                inf3Buff.write((normAbO.get(12)).toString() + "," + (normAbS.get(12)).toString());
                inf3Buff.newLine();
                }
                avAbsO.clear();
                avAbsS.clear();
            
        }
        
   callRCommand(rFileInf1);
   callRCommand(rFileInf2);
   callRCommand(rFileInf3);  
   writeBuff.close();
   inf1Buff.close();
   inf2Buff.close();
   inf3Buff.close();
   
   System.out.println("Summary File Created");     
   }
   
   public static void callRCommand(String inputFile){

        String rFile = "C:/Users/mackak/Documents/Officials/PlatformComparison/platformComparison_AbundanceCorrOvS_templateThreshold.r";

        try{
            File f = new File(rFile);
            FileInputStream fin = new FileInputStream(f);
            BufferedReader bin = new BufferedReader(new InputStreamReader(fin));

            int counter = 0;

            String rFunction = "";
            String temp;
            rFunction += "\n\n inputFile<-(\"" + inputFile + "\")\n" ;
            while((temp = bin.readLine()) != null){

                rFunction += temp + "\n";

            }         

            File fout = new File("C:/Users/mackak/Documents/Officials/PlatformComparison/rCorr.r");
            FileOutputStream out; // declare a file output object
            PrintStream p; // declare a print stream object

            try
            {
                out = new FileOutputStream(fout);
                p = new PrintStream( out );
                p.print (rFunction);

                p.close();
                out.close();
            }
            catch (Exception e)
            {
                    System.err.println ("Error writing to file");
            }


            //System.out.println(rFunction);

            try {
                Runtime rt = Runtime.getRuntime();
                //Process pr = rt.exec("cmd /c dir");
                Process pr = rt.exec("C:/Program Files/R/R-2.15.1/bin/R.exe CMD BATCH C:/Users/mackak/Documents/Officials/PlatformComparison/rCorr.r");

                BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

                String line=null;

                while((line=input.readLine()) != null) {
                    System.out.println(line);
                }

                int exitVal = pr.waitFor();
                System.out.println("Exited with error code "+exitVal + " (error code 0 indicates that R has run successfully)");

            }
            catch(Exception e) {
                System.out.println(e.toString());
                e.printStackTrace();
            }


        }
        catch(IOException e){
            e.printStackTrace();
        }
    }
   
}
